package com.live.activity;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.live.task.LiveVideoWatch;

public class LiveVideoActivity extends LiveBaseActivity {
	private WebView webView;
	private LinearLayout liveView;
	private LinearLayout loadData;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.live_video);

		/* 获取Intent中的Bundle对象 */
		Bundle bundle = this.getIntent().getExtras();

		TextView videoTitle = (TextView) findViewById(R.id.videoTitle);
		videoTitle.setText(bundle.getString("videoTitle"));

		liveView = (LinearLayout) findViewById(R.id.liveView);
		loadData = (LinearLayout) findViewById(R.id.loadData);

		webView = (WebView) findViewById(R.id.liveVideo);

		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setAllowFileAccess(true);
		webView.getSettings().setPluginsEnabled(true);
		webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
		webView.setWebChromeClient(new WebChromeClient() {
			public void onProgressChanged(WebView view, int progress) {
				// Activity和Webview根据加载程度决定进度条的进度大小
				if (progress == 100) {

					liveView.removeView(loadData);
				}
			}
		});

		LiveVideoWatch task = new LiveVideoWatch(context, webView);
		task.execute(bundle);
	}

	@Override
	protected void onPause() {
		super.onPause();

		callHiddenWebViewMethod("onPause");

		webView.pauseTimers();
		if (isFinishing()) {
			webView.loadUrl("about:blank");
			setContentView(new FrameLayout(this));
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		callHiddenWebViewMethod("onResume");

		webView.resumeTimers();
	}

	private void callHiddenWebViewMethod(String name) {
		// credits: http://stackoverflow.com/questions/3431351/
		// how-do-i-pause-flash-content-in-an-android-webview-when-my-activity-isnt-visible
		if (webView != null) {
			try {
				Method method = WebView.class.getMethod(name);
				method.invoke(webView);
			} catch (NoSuchMethodException e) {
				Log.d("flv", "No such method: " + name + e);
			} catch (IllegalAccessException e) {
				Log.d("flv", "Illegal Access: " + name + e);
			} catch (InvocationTargetException e) {
				Log.d("flv", "Invocation Target Exception: " + name + e);
			}
		}
	}

}